import { CSSProperties, FC, useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { View, Image, Text } from "@tarojs/components";
import { fetchUpload } from "@/service/common";
import styles from "./index.module.less";
import HIcon from "../Icon";
import { API_HOST } from "@/constants/host";

interface Props {
  /** 默认值 */
  defaultValue?: string[];
  /**上传按钮 */
  className?: CSSProperties;
  /**图片预览样式 */
  imgStyle?: CSSProperties;
  /**一次性上传图片数量,单选count=1就ok */
  count?: number;
  /**上传成功回调 */
  onSuccess?: (value: string[]) => void;
  /**删除图片回调， value：删除后的图片列表, index:删除的图片下标 */
  onRemove?: (value: string[], index: number) => void;
}

const Upload: FC<Props> = (props) => {
  const { count = 9, defaultValue, onSuccess, onRemove } = props;
  const [imgList, setImgList] = useState<string[]>(defaultValue || []);

  /**选择图片 */
  const onAdd = () => {
    Taro.chooseImage({
      // 默认9
      count: count,
      // 可以指定是原图还是压缩图，默认二者都有
      sizeType: ["original", "compressed"],
      // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      sourceType: ["album", "camera"],
      success: ({ tempFilePaths }) => {
        Taro.showLoading({ title: "图片上传中" });
        executeUpload(tempFilePaths);
      },
    });
  };

  /**文件上传 */
  const executeUpload = async (tempFilePaths: string[]) => {
    if (tempFilePaths.length !== 0) {
      const { res, err } = await fetchUpload(tempFilePaths[0]);
      if (res) {
        tempFilePaths.shift();
        /**直接push不会触发视图更新 */
        imgList.push(res.data.url);
        setImgList([...imgList]);
        return executeUpload(tempFilePaths);
      }
      return Taro.hideLoading();
    }
    Taro.hideLoading();
    Taro.showToast({ title: "图片上传成功", icon: "none" });
    onSuccess && onSuccess([...imgList]);
  };

  /**静态删除已上传的图片 */
  const onRemoveStaticImg = (path: string) => {
    const deleteImgIndex = imgList.findIndex((item) => item === path);
    const result = imgList.filter((item) => item !== path);
    setImgList([...result]);
    onRemove && onRemove([...result], deleteImgIndex);
  };

  function renderUploadBtn() {
    if (imgList.length < count) {
      return (
        <View
          className={`${styles["upload-btn"]}  ${props.className}`}
          onClick={onAdd}
        >
          <HIcon type="xiangji" size={42} color="#999" />
          {/* <Text className={styles["text"]}>添加图片</Text> */}
        </View>
      );
    }
  }

  return (
    <View className={styles["upload-wrapper"]}>
      <View className={styles["img-list"]}>
        {imgList.map((imgItem) => (
          <View className={`${styles["img-item"]} ${props.imgStyle}`}>
            <Image
              mode="widthFix"
              className={styles["img"]}
              src={API_HOST + imgItem}
            />
            <Text
              className={styles["close"]}
              onClick={() => onRemoveStaticImg(imgItem)}
            >
              x
            </Text>
          </View>
        ))}
      </View>
      {renderUploadBtn()}
    </View>
  );
};

export default Upload;
